package com.example.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.config.AliPayConfig;
import com.example.dto.OrdersDetailVDto;
import com.example.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AlipayClient alipayClient;
    @Autowired
    private AliPayConfig aliPayConfig;

    @GetMapping("alipay")
    public ResponseEntity<String> alipay(@RequestParam Integer orderId) {
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(aliPayConfig.getRETURN_URL());
        request.setNotifyUrl(aliPayConfig.getNOTIFY_URL());

        OrdersDetailVDto order = ordersMapper.selectDetailById(orderId);
        String out_trade_no = orderId.toString();
        String total_amount = order.getPrice().toString();
        String subject = "熙心健康体检";
        String body = order.getName();
        request.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_HTML);
            return new ResponseEntity<>(form, headers, HttpStatus.OK);
        } catch (AlipayApiException e) {
            log.error("调用支付宝异常", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("调用支付宝失败");
        }
    }

    @GetMapping(value = "/returnUrl")
    public void returnUrl(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = String.join(",", values);
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name, valueStr);
        }
        log.info("支付宝回调请求参数: {}", params);

        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                aliPayConfig.getALIPAY_PUBLIC_KEY(), aliPayConfig.getCHARSET(),
                aliPayConfig.getSIGN_TYPE());

        if (signVerified) {
            response.sendRedirect("http://localhost:5173/appointmentsuccess");
        } else {
            response.sendRedirect("http://localhost:5173/appointmentfail");
        }
    }
}
